package org.springblade.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
public class StreamUtils {

	private StreamUtils() {
	}

	/**
	 * Function 异常抛出
	 *
	 * @param mapper
	 * @param <T>
	 * @param <R>
	 * @return
	 */
	public static <T, R> Function<T, R> ofFunction(StreamExceptionFunction<T, R> mapper) {
		Objects.requireNonNull(mapper);
		return t -> {
			try {
				return mapper.apply(t);
			} catch (Exception e) {
				log.error("stream ", e);
				RuntimeException ex = new RuntimeException(e);
				throw ex;
			}
		};

	}


	/**
	 * Consumer 异常抛出
	 *
	 * @param mapper
	 * @param <T>
	 * @return
	 */
	public static <T> Consumer<T> ofConsumer(StreamExceptionConsumer<T> mapper) {
		Objects.requireNonNull(mapper);
		return t -> {
			try {
				mapper.accept(t);
			} catch (Exception e) {
				log.error("stream ", e);
				RuntimeException ex = new RuntimeException(e);
				throw ex;
			}
		};

	}

	/**
	 * Stream Function 异常处理
	 *
	 * @param <T>
	 * @param <R>
	 */
	@FunctionalInterface
	public interface StreamExceptionFunction<T, R> {
		R apply(T t) throws RuntimeException;
	}

	/**
	 * Stream Function 异常处理
	 *
	 * @param <T>
	 */
	@FunctionalInterface
	public interface StreamExceptionConsumer<T> {
		void accept(T t) throws RuntimeException, ExecutionException, InterruptedException;
	}
}



